import psutil
import sys
import re
import ctypes


def ProgramUnique(func):
	"""
	装饰器：检测该程序实例是否已经运行
	:param func: 被装饰的函数
	:return:
	"""
	# 绝对路径 ：sys.argv[0]
	symbol = re.match(r"^[A-Z]:(.).+", sys.argv[0]).group(1)
	if symbol == "/":
		file_name = sys.argv[0].split("/")[-1]
	elif symbol == "\\":
		file_name = sys.argv[0].split("\\")[-1]
	else:
		ctypes.windll.user32.MessageBoxA(0, u"获取系统异常".encode("gbk"), u'异常'.encode("gbk"), 0)
		sys.exit()

	if file_name == "***.exe": # ***.exe : 当前文件名
		def inner(*args, **kwargs):
			pids = psutil.pids()
			py_list = []
			i = 1
			for pid in pids:
				p = psutil.Process(pid)
				p_name = p.name()
				if p_name == "***.exe": # ***.exe : 当前文程序名
					py_list.append(p_name)
				i += 1

			if len(py_list) > 1:
				ctypes.windll.user32.MessageBoxA(0, u"已有程序在运行...".encode("gbk"),
												 u'异常'.encode("gbk"), 0)
				sys.exit()
			else:
				func(*args, **kwargs)
	else:
		ctypes.windll.user32.MessageBoxA(0, u"请勿修改程序名".encode("gbk"), u'异常'.encode("gbk"), 0)
		sys.exit()

	return inner




if __name__ == '__main__':
	# 例如
	@ProgramUnique
	def a():
		print(61)



	a()